package com.dominator.utils.wechat.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.math.BigDecimal;
import java.util.*;


import com.alibaba.fastjson.JSONObject;
import com.dominFramework.core.typewrap.Dto;
import com.dominFramework.core.utils.JsonUtils;
import net.sf.json.xml.XMLSerializer;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;


public class XMLUtils {


	@SuppressWarnings("rawtypes")
	public static String getRequestXml(TreeMap<String, String> parameters)
			throws Exception {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		Set es = parameters.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if ("mch_id".equalsIgnoreCase(k) || "nonce_str".equalsIgnoreCase(k)
					|| "sign".equalsIgnoreCase(k)) {
				sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
			} else {
				sb.append("<" + k + ">" + v + "</" + k + ">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}

	@SuppressWarnings("unchecked")
	public static String Progress_resultParseXml(String xml) {
		String publicKey = null;
		try {
			StringReader read = new StringReader(xml);
			InputSource source = new InputSource(read);
			SAXBuilder sb = new SAXBuilder();
			Document doc =  sb.build(source);
			Element root = doc.getRootElement();
			List<Element> list = root.getChildren();
			if (list != null && list.size() > 0) {
				for (org.jdom.Element element : list) {
					if("pub_key".equals(element.getName())){
						publicKey=element.getText();
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return publicKey;
	}



	public static JSONObject xml2JSON(byte[] xml) throws JDOMException, IOException {
		JSONObject json = new JSONObject();
		InputStream is = new ByteArrayInputStream(xml);
		SAXBuilder sb = new SAXBuilder();
		Document doc = sb.build(is);
		Element root = doc.getRootElement();
		json.put(root.getName(), iterateElement(root));
		return json;
	}

	private static JSONObject iterateElement(Element element) {
		List node = element.getChildren();
		Element et = null;
		JSONObject obj = new JSONObject();
		List list = null;
		for (int i = 0; i < node.size(); i++) {
			list = new LinkedList();
			et = (Element) node.get(i);
			if (et.getTextTrim().equals("")) {
				if (et.getChildren().size() == 0)
					continue;
				if (obj.containsKey(et.getName())) {
					list = (List) obj.get(et.getName());
				}
				list.add(iterateElement(et));
				obj.put(et.getName(), list);
			} else {
				if (obj.containsKey(et.getName())) {
					list = (List) obj.get(et.getName());
				}
				list.add(et.getTextTrim());
				obj.put(et.getName(), list);
			}
		}
		return obj;
	}

	public static String xmlToJson(String xml) {

		XMLSerializer serializer = new XMLSerializer();

		return serializer.read(xml).toString();

	}


	public static void main(String[] args) throws JDOMException, IOException {
		String successRes="<xml>\n" +
				"<return_code><![CDATA[SUCCESS]]></return_code>\n" +
				"<return_msg><![CDATA[支付成功]]></return_msg>\n" +
				"<result_code><![CDATA[SUCCESS]]></result_code>\n" +
				"<err_code><![CDATA[SUCCESS]]></err_code>\n" +
				"<err_code_des><![CDATA[微信侧受理成功]]></err_code_des>\n" +
				"<nonce_str><![CDATA[50780e0cca98c8c8e814883e5caa672e]]></nonce_str>\n" +
				"<mch_id><![CDATA[2302758702]]></mch_id>\n" +
				"<partner_trade_no><![CDATA[1212121221278]]></partner_trade_no>\n" +
				"<amount>500</amount>\n" +
				"<payment_no><![CDATA[10000600500852017030900000020006012]]></payment_no>\n" +
				"<cmms_amt>0</cmms_amt>\n" +
				"</xml>";

        String res=xmlToJson(successRes);
		System.out.println(res);
		Dto dto=JsonUtils.toDto(res);
        Integer amount=new BigDecimal(1.5).multiply(new BigDecimal(100)).intValue();
		dto.put("amount",amount);
		System.out.println(dto.toString());



	}
}